<?php


namespace app\cms\model;


use app\cms\community\lib\QueryModel;
use iflow\Response;

class sysRoleModel extends QueryModel
{

    protected $table = 'sys_role_table';

    public function getRoleList(string $user_role_name = ""): Response
    {
        $query = $this->where([
            'status' => 1
        ]) -> order([
            'create_time' => 'desc'
        ]);

        if ($user_role_name !== '') {
            $query -> whereLike('user_role_name', "%{$user_role_name}%");
        }
        $query = $query -> paginate([
            'page' => request() -> getParams('page'),
            'list_rows' => 10
        ]);
        $items = $query -> items();
        return $items? message() -> success('查询成功', $items, [
            'count' => $query -> total(),
            'page' => $query -> lastPage()
        ]): message() -> nodata('暂无权限列表');
    }

    public function deleteRole(int $user_role_id): Response
    {
        $use = (new userRoleModel()) -> where([
            'user_role_id' => $user_role_id
        ]) -> findOrEmpty();

        $adminUse = (new adminUseRoleModel()) -> where([
            'user_role_id' => $user_role_id
        ]) -> findOrEmpty();

        if ($use -> isExists() || $adminUse -> isExists()) return message() -> update_failed('删除失败, 该权限已有用户正在使用');

        $del = $this->where([
            'user_role_id' => $user_role_id
        ]) -> delete();

        return $del ? message() -> success('删除成功') :
            message() -> update_failed('删除失败');
    }

    public function addRoleInfo(string $user_role_name, string $user_role_path, string $user_role_description): Response
    {
        $create = self::create([
            'user_role_name' => $user_role_name,
            'user_role_path' => $user_role_path,
            'user_role_description' => $user_role_description,
        ]) -> toArray();

        if (empty($create['id'])) return message() -> update_failed('创建权限失败');

        $create['user_role_id'] = $create['id'];
        return message() -> success('创建成功', $create);
    }
}